import sys
from socket import *
from time import sleep
import getpass

def menu():
    menu = """
        ==================== Welcome ======================


                        1.登录      2.注册                  


        ===================================================
    """
    print(menu)

def do_work(connfd):
    while True:
        work = input("please input work you want search >>")
        if work == '':
            print("exit")
            connfd.send(b'E')
            sleep(2)
            break
        connfd.send(work.encode())
        data = connfd.recv(1024).decode()
        if not data:
            break
        print(data)



def login(connfd):
    # 向服务器发起登录请求
    connfd.send(b'L')
    # 服务器：返回ok 表示确认可以登录
    data = connfd.recv(64).decode()
    if data != "OK":
        return
    user = input("user name >")
    if user == '':
        sys.exit('exit')
    passwd = getpass.getpass("password >")
    if passwd == '':
        sys.exit('exit')
    tmp = user + '\t' + passwd
    # 将用户名密码发送给服务器
    connfd.send(tmp.encode())
    # 接收服务器反馈
    message = connfd.recv(1024).decode()
    print(message)
    if message == 'login successfully':
        do_work(connfd)

def register(connfd):
    connfd.send(b'R')
    data = connfd.recv(64).decode()
    if data != "YES":
        return 
    user = input("user name >")
    passwd = input("passwd >")
    tmp = user + '\t' + passwd
    connfd.send(tmp.encode())
    message = connfd.recv(1024).decode()
    print(message)


def start(sockfd):
    try:
        while True:
            menu()
            choise = input(">")
            if choise == '1':
                #登录
                login(sockfd)
            elif choise == '2':
                #注册
                register(sockfd)
            elif choise == '':
                sys.exit("退出程序")
    except KeyboardInterrupt:
        sys.exit(" Thank for use")


def main():
    sockfd = socket()
    sock_addr = ('127.0.0.1',8888)
    sockfd.connect(sock_addr)
    start(sockfd)
if __name__ == "__main__":
    main()

